package com.demo.hxs.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.demo.hxs.entity.OrderTable;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class ExcelExportToConsoleService {

    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    // 利用多线程加速打印excel中数据到控制台
    public void exportToConsole() {
        long start = System.currentTimeMillis();
        // 1. 读取Excel文件（使用EasyExcel）
        List<OrderTable> dataList = EasyExcel.read("C:\\Users\\123\\Desktop\\orders.xlsx")
                .head(OrderTable.class)
                .sheet("Sheet2")
                .doReadSync();

        // 2.处理并提交任务
        for (OrderTable orderTable : dataList) {
            taskExecutor.execute(()->{
                System.out.println(Thread.currentThread().getName()+":"+orderTable);
                try {
                    Thread.sleep(2000);
                }catch (InterruptedException e){
                    throw new RuntimeException(e);
                }
            });
        }

        // 3.关闭线程池，防止资源泄露
        taskExecutor.shutdown();
        long end = System.currentTimeMillis();
        System.out.println("利用多线程导出orders.xlsx全量数据到idea控制台耗时："+(end-start)+"ms");
    }

    // 打印excel中数据到控制台
    public void export(){
        long start = System.currentTimeMillis();
        String fileName="C:\\Users\\123\\Desktop\\orders.xlsx";

        // 用于存储读取的数据
        List<OrderTable> list=new ArrayList<>();

        // 读取excel文件
        EasyExcel.read(fileName, OrderTable.class, new ReadListener<OrderTable>() {
            @Override
            public void invoke(OrderTable orderTable, AnalysisContext analysisContext) {
                // 每读取一行数据，就调用此方法
                list.add(orderTable);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                // 读取完成后调用此方法
                System.out.println("excel文件读取完成");
            }
        }).sheet().doRead();
        // 将数据导入idea中
        for (OrderTable orderTable : list) {
            System.out.println(orderTable);
        }
        long end = System.currentTimeMillis();
        System.out.println("导出orders.xlsx全量数据到idea控制台耗时："+(end-start)+"ms");
    }
}
